//
//  PopoverViewController.swift
//  KKViewController_Animation
//
//  Created by liaozhenming on 2016/12/15.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

import UIKit
import Foundation

extension UIViewController {
    
    class KKPopoverModel: NSObject {
        static let sharedInstance = KKPopoverModel()
        var backgroundView = UIView.init(frame: UIScreen.main.bounds)
        var backgroundImageView: UIImageView = UIImageView.init(frame: UIScreen.main.bounds)
        var shadowView: UIView = UIView.init(frame: UIScreen.main.bounds)
        weak var popoverViewController: UIViewController?
        
        override init() {
            super.init()
            backgroundView.backgroundColor = UIColor.black
            backgroundView.addSubview(backgroundImageView)
            backgroundView.addSubview(shadowView)
        }
        
        public func screenShotImage(layer: CALayer) {
            UIGraphicsBeginImageContext(layer.frame.size)
            let context = UIGraphicsGetCurrentContext()
            layer.render(in: context!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.backgroundImageView.image = image
        }
    }
    
    //  MARK: 公开方法
    public func kk_popover(_ viewControllerToPopover: UIViewController) {
        self.kk_popover(viewControllerToPopover, displayScale: 0.8)
    }
    
    //  displayScale 为显示区域的高度比值（0 - 1.0之间）
    public func kk_popover(_ viewControllerToPopover: UIViewController, displayScale: Double) {
        let sharedInstance = KKPopoverModel.sharedInstance
        sharedInstance.popoverViewController = viewControllerToPopover
        
        var currentScale = displayScale
        if displayScale <= 0 || displayScale >= 1.0 {
            currentScale = 0.8
        }
        
        var targetVC = self
        if self.navigationController != nil {
            targetVC = self.navigationController!
        }
        
        //
        targetVC.addChild(viewControllerToPopover)
        
        let popoverView = viewControllerToPopover.view
        let screenHeight = UIScreen.main.bounds.height
        let screenWidth = UIScreen.main.bounds.width
        
        popoverView?.frame = CGRect(x: 0, y: screenHeight * CGFloat(1 - currentScale) + screenHeight, width: screenWidth, height: screenHeight * CGFloat(currentScale))
        sharedInstance.shadowView.alpha = CGFloat.leastNormalMagnitude
        sharedInstance.shadowView.backgroundColor = UIColor.init(white: 0.0, alpha: 0.5)
        sharedInstance.screenShotImage(layer: targetVC.view.layer)
        targetVC.view.addSubview(sharedInstance.backgroundView)
        targetVC.view.addSubview(popoverView!)
        
        sharedInstance.shadowView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(UIViewController.popover_onTap(_:))))
        
        self.popover_open()
    }
    
    public func kk_disPopover(){
        let sharedInstance = KKPopoverModel.sharedInstance
        if sharedInstance.popoverViewController == self {
            self.popover_close()
        }
    }
    
    @objc func popover_onTap(_ tapper:UITapGestureRecognizer) {
        self.popover_close()
    }
    
    //  MARK: 私有方法 不公开
    
    private func popover_open() {
        
        let sharedInstance = KKPopoverModel.sharedInstance
        
        let popoverView = sharedInstance.popoverViewController?.view
        let screenHeight = UIScreen.main.bounds.height
        let screenWidth = UIScreen.main.bounds.width
        
        UIView.animate(withDuration: 0.35, animations: {()->Void in
            sharedInstance.backgroundImageView.transform = CGAffineTransform.init(scaleX: 0.9, y: 0.9)
            sharedInstance.shadowView.alpha = 1.0
            popoverView?.center = CGPoint(x: screenWidth/2.0, y: screenHeight - (popoverView?.bounds.size.height)!/2.0)
        }, completion: {(finished: Bool) -> Void in
            sharedInstance.shadowView.center = CGPoint(x: screenWidth/2.0, y: screenHeight/2 - (popoverView?.bounds.size.height)!)
        })
    }
    
    private func popover_close() {
        
        let sharedInstance = KKPopoverModel.sharedInstance
        let popoverView = sharedInstance.popoverViewController?.view
        let screenHeight = UIScreen.main.bounds.height
        let screenWidth = UIScreen.main.bounds.width
        
        UIView.animate(withDuration: 0.35, animations: {()->Void in
            sharedInstance.backgroundImageView.transform = CGAffineTransform.identity
            sharedInstance.shadowView.alpha = CGFloat.leastNormalMagnitude
            popoverView?.center = CGPoint(x: screenWidth/2.0, y: screenHeight + (popoverView?.bounds.size.height)!/2.0)
            sharedInstance.shadowView.center = CGPoint(x: screenWidth/2.0, y: screenHeight/2)
        }, completion: {(finished: Bool) -> Void in
            
            popoverView?.removeFromSuperview()
            sharedInstance.backgroundView.removeFromSuperview()
            sharedInstance.popoverViewController?.removeFromParentViewController()
        })
    }
}
